<template>
  <div class="upload-file">
    <input type="file" name="" id="" @change="getInpntValue" ref="upload" style="display:none">
    <ul v-if="filesList && filesList.length > 0" class="file-list">
      <li v-for="(item, index) in filesList" :key="item.id" class="list-item">
        <div @click="download(item.url, item.filename)">
          <img
            :src="(item.filetype && item.filetype.includes('image')) || (item.suffix && imgType.includes(item.suffix.toLowerCase())) ? item.url : defaultIcon"
            lazy/>
        </div>
        <span :title="item.filename" class="hidden-text-1 item-name">{{item.filename || 'kkk'}}</span>
        <i class="el-icon-delete delete" title="删除" @click="deleteItem(index, item)" v-if="formType !== 'see'"></i>
      </li>
    </ul>
    <div v-if="!filesList.length && formType === 'see'" style="color:#ccc">暂无文件</div>
    <el-button type="primary" @click="upload()" size="mini" :loading="loading" v-if="filesList && filesList.length < max && formType !== 'see'">上传文件(最多上传{{max}}个)</el-button>
  </div>
</template>
<script>
export default {
  components: {},
  props: {
    formType: {},
    value: {},
    formData: {},
    filesList: {
      type: [Array, null],
      default: () => []
    },
    max: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      defaultIcon: require('../../assets/images/file_icon.png'),
      currentValue: '',
      loading: false,
      imgType: ['png', 'jpg', 'gif', 'jpeg', 'webp', 'svg', 'tif']
    };
  },
  computed: {

  },
  mounted() {},
  methods: {
    deleteItem(index, item) {
      this.$confirm(`您真的要删除此文件吗`, `温馨提示`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.$emit('delete', {index, item})
      })
    },
    upload() {
      this.$refs.upload.click()
    },
    async download(url, name) {
      const blob = await this.getBlob(url)
      this.saveAs(blob, name)
    },
    getBlob(url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        // 避免 200 from disk cache
        url = url + `?r=${Math.random()}`
        xhr.open('GET', url, true)
        xhr.responseType = 'blob'
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response)
          }
        }
        xhr.send()
      })
    },
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        const anchor = document.createElement('a')
        const body = document.querySelector('body')
        anchor.href = window.URL.createObjectURL(blob)
        anchor.download = filename

        anchor.style.display = 'none'
        body.appendChild(anchor)

        anchor.click()
        body.removeChild(anchor)

        window.URL.revokeObjectURL(anchor.href)
      }
    },
    async getInpntValue(e) {
      try {
        this.loading = true
        this.currentValue = e.target.files[0]
        console.log(this.currentValue, 'this.currentValue');
        let filetype = this.currentValue.type
        let filename = this.currentValue.name
        let size = this.currentValue.size

        // 大于4m的文件不能上传
        if (size > 4000 * 1024) {
          e.target.value = ''
          this.loading = false
          return this.$message('请上传小于4M的文件')
        }

        let data = new FormData()
        data.append('file', this.currentValue)
        // 加入额外参数
        if (this.formData) {
          Object.keys(this.formData).map(key => {
            data.append(key, this.formData[key])
          })
        }
        const res = await this.$api.filesUpload(data)
        this.loading = false
        e.target.value = ''
        if (res.code === '0') {
          this.$emit("change", {
            filename,
            filetype,
            filepath: res.data.url,
            url: res.data.url,
            id: res.data.id + ''
          })
        } else {
          this.$emit("change", {})
        }
      } catch (error) {
        this.loading = false
        e.target.value = ''
        this.$message({
          type: 'warning',
          message: '上传失败'
        })
      }
    }
  }
};
</script>
<style scope lang='scss'>
.file-list{
  display: flex;
  .list-item{
    cursor: pointer;
    list-style: none;
    border-radius: 10px;
    overflow: hidden;
    width: 100px;
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    .item-name{
      width: 100%;
    }
    .delete{
      position: absolute;
      right: 3px;
      top: 3px;
      color:red;
    }
    img {
      width: 100px;
      height: 100px;
      border: 1px solid #0095ff;
      border-radius: 10px;
      display: block;
    }
  }
  .list-item:last-child{
    margin-right: 0;
  }
}
</style>
